<?php
namespace app\crm\model;
use think\Model;
use think\Db;
use think\Cache;
use think\Loader;

class Outboundmanager extends Model
{   
    /**
     * 外呼列表
     * @return [type] [description]
     */
    public function outboundTaskData()
	{
		header("Content-Type:text/html; charset=utf-8");
		$page = $_REQUEST["page"];
		$limit = $_REQUEST["limit"];
		$count = Db::table("bgcrm.sales_task")->count();
		$dataList = Db::table("bgcrm.sales_task")->limit(($page-1)*$limit,$limit)->order("createtime desc")->select();
		$department = Cache::get('department');
		$users = Cache::get('users');
		$calltype = array("autocall"=>"自动外呼","preview"=>"预览式外呼");
		foreach($dataList as &$val){
			$val["d_name"] = $department[$val["dept_id"]]["department_name"];
			$val["createuser"] = $users[$val["createuser"]]["cn_name"];
			$val["calltype"] = $calltype[$val["calltype"]];
			if( file_exists("/var/tmp/autocall/bgcrm:" .$val['id'] ) ){
				$val["taskStatus"] = "运行";
			}else{
				$val["taskStatus"] = "停止";
			}
		}
		
		$rowsList = count($dataList) ? $dataList : false;
        $arrCate["code"] = 0;
        $arrCate["msg"] = '';
        $arrCate["count"] = $count;
        $arrCate["data"] = $rowsList;
		
		return $arrCate;
	}
	
	/**
     * 外呼会员资料列表
     * @return [type] [description]
     */
    public function saleSourceData($where)
	{
		header("Content-Type:text/html; charset=utf-8");
		
		$menuname = "Outbound Task List";
		$p_menuname = $_SESSION['menu'][$menuname]; //父菜单
		$priv = $_SESSION["user_priv"][$p_menuname][$menuname]; 
		$username = $_SESSION["user_info"]["username"];


		$page = $_REQUEST["page"];
		$limit = $_REQUEST["limit"];
		$id = $_REQUEST["id"];
		$count = Db::table("bgcrm.sales_source_$id")->where($where)->count();
		$dataList = Db::table("bgcrm.sales_source_$id")->where($where)->limit(($page-1)*$limit,$limit)->order("createtime desc")->select();
		$users = Cache::get('users');
		$calledflag = array("1"=>"未呼叫","2"=>"未接听","3"=>"已接听");
		$i = 0;
		foreach($dataList as &$val){
			$val["createuser"] = $users[$val["createuser"]]["cn_name"];
			$val["calledflag"] = $calledflag[$val["calledflag"]];
			$i++;
			
			if($priv["encrypt_phone"] == "Y"){
			    if($username != "admin"){
			        $val["phone1"] = substr($val["phone1"],0,3)."*****".substr($val["phone1"],-2);
			        $val["phone2"] = substr($val["phone2"],0,3)."*****".substr($val["phone2"],-2);
			    }
			}
		}
		unset($i);
		$rowsList = count($dataList) ? $dataList : false;
        $arrCate["code"] = 0;
        $arrCate["msg"] = '';
        $arrCate["count"] = $count;
        $arrCate["data"] = $rowsList;
		
		return $arrCate;
	}
	
	
	public function getTaskUsers()
	{
		$arrUData = Db::name('sys_users')->order("username asc")->field("username,cn_name")->select();
		
		
		return $arrUData;
	}
	
	
	public function getTaskIVR()
	{
		$tpl_ivr = Db::table('asterisk.recordings')->field('id,displayname')->select();
		
		return $tpl_ivr;
	}

	public function getTaskTrunks()
	{
		$arrT = Db::table('asterisk.trunks')->select();
		$tpl_trunks = Array();
		foreach( $arrT AS $v ){
			if($v['tech']=='zap' or $v['tech']=='dahdi'){
				$tpl_trunks[] = Array("name"=>"DAHDI/".$v['channelid']);
			}elseif($v['tech']=='sip'){
				$tpl_trunks[] = Array("name"=>"SIP/".$v['channelid']);
			}elseif($v['tech']=='iax2'){
				$tpl_trunks[] = Array("name"=>"IAX2/".$v['channelid']);
			}else{
				;
			}
		}
		
		return $tpl_trunks;
	}
	
	public function insertTask()
	{
		$d_id = (int)$_POST['dept_id_queue'];
		$arrUsers = $_REQUEST["join_queue_method2"];
		$agent_task = implode(",",$arrUsers);
		$arrTask = array(
			'name'=> $_POST['name'],
			'runtime'=> $_REQUEST['time_group'],
			'hangup_by_idle'=> $_REQUEST['hangup_by_idle'],
			'createuser'=> $_SESSION["user_info"]["username"],
			'calltype'=> $_POST['calltype'],
			'createtime'=> Date('Y-m-d H:i:s'),
			'describle'=> $_POST['describle'],
			'dept_id'=> $_POST['dept_id_queue'], //队列
			'toqueue_timeout'=> (int)$_POST['toqueue_timeout'],
			'maxrecall_times'=> (int)$_POST['maxrecall_times'],
			'concurrence'=> (int)$_POST['concurrence'],  //最大并发数
			'limitperselect'=> 100, //
			'answer_target'=> $_POST['answer_target'],
			'join_queue_method'=> $_POST['join_queue_method'],
			'trunk'=> $_REQUEST['trunk'],
			'area_code'=> $_REQUEST['area_code'],
			'callout_pre'=> $_POST['callout_pre'],
			'callerid'=> $_POST['callerid'],
			'idle_ratio'=> $_POST['idle_ratio'],
			'ivr_id'=> $_POST['ivr_id'],
			'save_not_dnd'=> $_POST['save_not_dnd'],
			'autocall_status'=> $_POST['autocall_status'],
			'use_meeting'=> empty($_POST['use_meeting']) ? "N" : $_POST['use_meeting'] ,
			'enable'=> 'Y', ///
			'qualitypercent'=> 0,//
			'needrecord'=> 'Y',
			'agent_task'=> $agent_task,
			
		);
		//dump($arrTask);die;
		$res = Db::table("bgcrm.sales_task")->insert($arrTask);
		$last_id = Db::table("bgcrm.sales_task")->getLastInsID();
		//dump( $sales_task->getLastSql() );die;
		
		//创建号码表
		//创建号码资源包的表名
		Db::table("bgcrm.sales_task")->execute("create table bgcrm.sales_source_$last_id like bgcrm.sales_source");
		Db::table("bgcrm.sales_task")->execute("create table bgcrm.sales_cdr_$last_id like bgcrm.sales_cdr");
			
		//添加队列设置-----此段代码等有时间后调整
		$file_contents = file_get_contents('http://192.168.88.59:8888/index.php?m=FishCRM&a=insertTask&calltype='.$_POST['calltype'].'&last_id='.$last_id);
		if ($res){
			echo json_encode(array('success'=>true,'msg'=>'添加成功'));
		} else {
			echo json_encode(array('msg'=>'添加失败'));
		}
	}

	public function updateTask()
	{
		$d_id = (int)$_POST['dept_id_queue'];
		$arrUsers = $_REQUEST["join_queue_method2"];
		$agent_task = implode(",",$arrUsers);
		$arrTask = array(
			'id'=> $_REQUEST['id'],
			'name'=> $_POST['name'],
			'runtime'=> $_REQUEST['time_group'],
			'hangup_by_idle'=> $_REQUEST['hangup_by_idle'],
			'createuser'=> $_SESSION["user_info"]["username"],
			'calltype'=> $_POST['calltype'],
			'createtime'=> Date('Y-m-d H:i:s'),
			'describle'=> $_POST['describle'],
			'dept_id'=> $_POST['dept_id_queue'], //队列
			'toqueue_timeout'=> (int)$_POST['toqueue_timeout'],
			'maxrecall_times'=> (int)$_POST['maxrecall_times'],
			'concurrence'=> (int)$_POST['concurrence'],  //最大并发数
			'limitperselect'=> 100, //
			'answer_target'=> $_POST['answer_target'],
			'join_queue_method'=> $_POST['join_queue_method'],
			'trunk'=> $_REQUEST['trunk'],
			'area_code'=> $_REQUEST['area_code'],
			'callout_pre'=> $_POST['callout_pre'],
			'callerid'=> $_POST['callerid'],
			'idle_ratio'=> $_POST['idle_ratio'],
			'ivr_id'=> $_POST['ivr_id'],
			'save_not_dnd'=> $_POST['save_not_dnd'],
			'autocall_status'=> $_POST['autocall_status'],
			'use_meeting'=> empty($_POST['use_meeting']) ? "N" : $_POST['use_meeting'] ,
			'enable'=> 'Y', ///
			'qualitypercent'=> 0,//
			'needrecord'=> 'Y',
			'agent_task'=> $agent_task,
			
		);
		//dump($arrTask);die;
		$res = Db::table("bgcrm.sales_task")->update($arrTask);
		if ($res){
			echo json_encode(array('success'=>true,'msg'=>'编辑成功'));
		} else {
			echo json_encode(array('msg'=>'编辑失败'));
		}
	}
	
	public function getTaskData($id)
	{
		$taskData = Db::table("bgcrm.sales_task")->where("id",$id)->find();
		return $taskData;
	}


	/**
	 * 通话记录
	 * @param  string $id    任务id
	 * @param  string $where 搜索条件
	 * @return array         通话记录数据
	 */
	public function taskRecordsList($id, $where)
	{
		$page = $_REQUEST["page"];
		$limit = $_REQUEST["limit"];
		$count = Db::table("bgcrm.sales_cdr_$id")->where($where)->count();
		// 查询状态为1的用户数据 并且每页显示10条数据
		$taskList = Db::table("bgcrm.sales_cdr_$id")->where($where)->limit(($page-1)*$limit,$limit)->select();
		// echo $taskList;exit;
		// print_r($taskList);exit;
		$cdr_status_row = array('ANSWERED'=>'转人工已接','AUTOCALL'=>'外呼失败','NO ANSWER'=>'转人工未接','PLAYIVR'=>"未转接",'BUSY'=>'忙',"FAILED"=>"外呼失败");
		$cdr_calltype_row = array('preview'=>'预览式外呼','autocall'=>'自动外呼');
		$success_row = array('Y'=>'成功单录音','N'=>'非成功单录音');
		foreach ($taskList as &$val) {
			$status = $cdr_status_row[$val["disposition"]];
			$val["disposition"] = $status;
			$calltypes = $cdr_calltype_row[$val["calltype"]];
			$val["calltype"] = $calltypes;
			$success_enable = $success_row[$val["success_enable"]];
			$val["success_enable"] = $success_enable;
			$val["billsec"] = sprintf("%02d",intval($val["billsec"]/3600)).":".sprintf("%02d",intval(($val["billsec"]%3600)/60)).":".sprintf("%02d",intval((($val[billsec]%3600)%60)));

		}
		$rowsList = count($taskList) ? $taskList : false;
		$arrData["code"] = 0;
		$arrData["msg"] = '';
		$arrData["count"] = $count;
		$arrData["data"] = $rowsList;
		return $arrData;
	}


	/**
	 * 获取任务控制数据
	 * @param  string $id 任务id
	 * @return array      任务控制数据
	 */
	public function dialManager ($id)
	{
		$total = Db::table("bgcrm.sales_source_$id")->count();
		$tpl_ST['total'] = $total; // 号码总量

		$calledCount = Db::table("bgcrm.sales_source_$id")->where("calledflag >1")->count();
		$tpl_ST['db_calledCount'] = $calledCount; // 已呼叫过的号码

		$progress = "";
		if($calledCount){
				//$calledCount = $arr[0]['calledCount'];
				$percent = sprintf("%01.2f",100*$calledCount/$total); //任务进度
				$progress = $percent;
		}else{
				$progress = "0";
		}
		$tpl_ST['progress'] = $progress;

		if( !file_exists("/var/tmp/autocall/bgcrm:$id") ){
			$arrTmp = Db::table("bgcrm.sales_task")->where("enable='Y' AND id=$id")->find();
			$tpl_ST['concurrence'] = $arrTmp['concurrence'];
		}

		return $tpl_ST;
	}

	public function customerCount ($id)
	{
		$count = Db::table("bgcrm.sales_source_$id")->count();
		return $count;
	}


	//复位呼叫失败的号码
	public function resetCallFailedNum(){
		$task_id = $_REQUEST['task_id'];
		if( $task_id ){
			$result = Db::table("bgcrm.sales_source_$task_id")->where('calledflag="2"')->update(array('calledflag'=>'1','locked'=>'N'));   //,callresult_id=1,dealresult_id=0 
			
			$username = $_SESSION['user_info']['username'];
			$enterprise_number = $_SESSION['user_info']['enterprise_number'];
			// $mod = M("task_operation");
			$arrData = array(
				"create_time"=>date("Y-m-d H:i:s"),
				"create_user"=>$username,
				"enterprise_number"=>$enterprise_number,
				"task_id"=>$task_id,
				"operation_type"=>"重置未接号码",
			);
			$result = Db::table("bgcrm.task_operation")->insert($arrData);
			echo json_encode(array('success'=>true,'msg'=>'重置成功'));
		}else{
			echo json_encode(array('msg'=>'重置失败'));
		}
	}
	


}